<?php
namespace app\admin\controller;

use app\BaseController;
use app\admin\service\Administrator as AdministratorService;
use think\facade\Db;
use app\admin\model\Administrator as AdministratorModel;

class Login extends BaseController
{
    public function index()
    {

        if ($this->app->request->isGet()) {
            if (AdministratorService::isLogin()) {
                $this->redirect(url('admin/index/index')->build());
            } else {
                // 加载登录模板
                $this->title = '系统登录';

                return view('index');
            }
        }else{
            $data = request()->post();
            $rule = [
                'username' => 'require'
                ,'password'  => 'require'
                ,'vercode' => 'require|captcha'
            ];
            $message = [
                'username.require'  =>  '用户名必须',
                'password.require' =>  '密码必填',
                'vercode.require' =>  '验证码必填',
                'vercode.captcha' =>  '验证码错误',
            ];
            try {
                $this->validate($data,$rule,$message);
            } catch (\Exception $e){
                $this->return($e->getMessage(),['status_code'=>-1]);
            }
            /*! 用户信息验证 */
            $map = ['username' => $data['username'], 'is_deleted' => 0];

            $adminModel = new AdministratorModel;
            $user = $adminModel::where($map)->findOrEmpty();
            if (empty($user)) {
                $this->return('登录账号错误，请重新输入!',['status_code'=>-1]);
            }

            if($user['password'] != $data['password']){
                $this->return('密码错误，请重新输入!',['status_code'=>-1]);
            }
            if (empty($user['status'])) {
                $this->return('账号已经被禁用，请联系管理员!',['status_code'=>-1]);
            }

            session('admins_id', $user['id']);
            session('admins_info',  $user);
            // 更新登录次数
            $adminModel->where('id' ,$user['id'])->inc('login_num')->update([
                'login_at' => date('Y-m-d H:i:s'), 'login_ip' => $this->app->request->ip(),
            ]);

            //菜单//TODO
            $data['access_token'] = md5(time().rand(1000,999999));
            $data['url'] = url('/admin/index/index')->build();
            $data['status_code'] = 0;
            $this->return('登录成功', $data);

        }

    }

    /**
     * 退出登录
     * @return void
     */
    public function out()
    {
        session(null);
        $this->return('退出登录成功!', url('admin/login/index')->build());
    }

}
